package com.rs.common.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.rs.common.dao.CommonDao;
import com.rs.common.entity.FenYe;

public class CommonDaoImpl<T> extends HibernateDaoSupport implements CommonDao<T> {

	public void addEntity(Object entity) {
		this.getHibernateTemplate().save(entity);
		
	}

	public void deleteEntityById(Class<T> entityClass, Serializable id) {
		
		this.getHibernateTemplate().delete(this.getEntityById(entityClass, id));
		
	}

	public T getEntityById(Class<T> entityClass, Serializable id) {
		
		return this.getHibernateTemplate().get(entityClass, id);
	}

	public List<T> getList(Class<T> entityClass, int nowPage, int pageSize) {
		
		return null;
	}

	public void updateEntity(Object entity) {
		this.getHibernateTemplate().update(entity);
		
	}
	
	public List<T> getList(final Class<T> entityClass,final FenYe fenYe) {
		// TODO Auto-generated method stub
		List<T> list = null;
		// 当当前页小于首页时为首页
		if (fenYe.getNowPage() <= 1) {
			fenYe.setNowPage(1);
		}
		// 没页的条数
		fenYe.setPageSize(6);
		 list=this.getHibernateTemplate().executeFind(new HibernateCallback() {

			public List doInHibernate(Session session) throws HibernateException,
					SQLException {
					Criteria c = session.createCriteria(entityClass);
					// 总条数
					fenYe.setTotalNums(c.list().size());
					// 总页数
					fenYe.setTotalPages((fenYe.getTotalNums() + fenYe.getPageSize() - 1)/ fenYe.getPageSize());
					// 当当前页大于末页时为末页
					if (fenYe.getNowPage() >= fenYe.getTotalPages()) {
						fenYe.setNowPage(fenYe.getTotalPages());
					}
					c.setFirstResult(fenYe.getPageSize() * (fenYe.getNowPage() - 1));
					c.setMaxResults(fenYe.getPageSize());
					// 把分页集合填满
				return c.list();
			}
		});
		return list;
	}

	
}
